<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */

namespace app\service\fetch\kuaishou;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\ClientAccountModel;
use app\model\KsActionBarModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\kuaishou\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Model;

final class ActionBarService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::LIST_CONFIG_LOCK_KEY]['action_bar'];

    /**
     * 获取行动号召.
     *
     * @param string $advertiserId 账户id
     */
    public static function getAction(string $advertiserId = ''): bool
    {
        $listType = array_keys(KuaiShouEnum::CAMPAIGN_TYPE);
        if (! $listType) {
            return self::setError('获取行动类型失败');
        }
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            $version = date('Ymd'); // 版本号
            $redis = Cache::store('redis')->handler();
            foreach ($listType as $type) {
                $result = self::getList($advertiserId, $type);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['action_bar_text']) == 0) {
                    break;
                }
                foreach ($result['data']['action_bar_text'] as $item) {
                    $model = self::getInfo($advertiserId, $type, $item);
                    if (! $model instanceof KsActionBarModel || ! $model->getKey()) {
                        $model = new KsActionBarModel();
                    }
                    $model->setAttrs([
                        'advertiser_id' => $advertiserId,
                        'account_id' => $obj->getKey(),
                        'campaign_type' => $type,
                        'action_bar_text' => $item,
                        'consult_type' => 0,
                        'version' => $version,
                    ]);
                    if (! $model->save()) {
                        throw new \Exception('保存数据出错');
                    }
                }
            }
            $redis->rPush(ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['action_bar_sync'], $advertiserId . '|' . $version);
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取行动号召列表.
     *
     * @param string $advertiserId 账户id
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', int $type = 2)
    {
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'campaign_type' => $type,
        ];
        return AdvertiserService::getActionList($headers, $params);
    }

    /**
     * 获取信息.
     * @param string $advertiserId 账户id
     * @param int $campaignType 计划类型
     * @param string $actionBarText 行动号召
     * @return null|array|KsActionBarModel|mixed|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', int $campaignType = 0, string $actionBarText = '')
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['campaign_type', '=', $campaignType],
            ['action_bar_text', '=', $actionBarText],
        ];
        return (new KsActionBarModel())->where($where)->field(true)->find();
    }
}
